<template>
  <div class="tag-manage">
    <div class="tag-input">
      <el-input v-model="newTag" size="small" @keyup.enter="handleAddTag" :placeholder="placeholder" ref="tagInputRef">
        <template #append>
          <el-button @click="handleAddTag">添加</el-button>
        </template>
      </el-input>
    </div>
    <div class="tag-box">
      <div class="tag-list" v-if="modelValue?.length">
        <el-tag v-for="(tag, index) in modelValue" :key="index" :closable="true" @close="handleRemoveTag(index)" effect="light" class="tag-item" type="success" size="small">{{ tag }}</el-tag>
      </div>
      <div class="tag-list empty-tags" v-else>
        <div class="tag-empty">暂无标签</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, defineProps, defineEmits } from 'vue'

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => [],
  },
  placeholder: {
    type: String,
    default: '输入标签按回车确认',
  },
})
console.log('加载了', props)
const emit = defineEmits(['update:modelValue'])

const newTag = ref('')
const tagInputRef = ref(null)

const handleAddTag = () => {
  if (newTag.value.trim()) {
    if (!props.modelValue.includes(newTag.value.trim())) {
      const updatedTags = [...props.modelValue, newTag.value.trim()]
      emit('update:modelValue', updatedTags)
    }
    newTag.value = ''
  }
}

const handleRemoveTag = (index) => {
  const updatedTags = [...props.modelValue]
  updatedTags.splice(index, 1)
  emit('update:modelValue', updatedTags)
}
</script>

<style lang="scss" scoped>
.tag-manage {
  .tag-box {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 8px;
    padding: 8px 16px;
    min-height: 32px;
    border-radius: 4px;
    background: var(--el-fill-color-lighter);

    .tag-list {
      display: flex;
      flex-wrap: wrap;
      gap: 6px;
      flex: 1;

      &.empty-tags {
        width: 100%;
        justify-content: center;
        opacity: 0.7;
      }
    }

    .tag-item {
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      }
    }

    .tag-input {
      flex: 1;
      min-width: 200px;
      margin-top: 8px;
    }
  }
}
</style>
